package core.util.popup
{
	import flash.display.DisplayObject;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.core.Application;
	import mx.core.FlexGlobals;
	import mx.core.IFlexDisplayObject;
	import mx.effects.Fade;
	import mx.effects.Move;
	import mx.effects.Parallel;
	import mx.events.EffectEvent;
	import mx.managers.PopUpManager;

	public class PopUpAutoCloseWindow implements IPopUp
	{
		public function PopUpAutoCloseWindow()
		{
		}
		private static var instance:PopUpAutoCloseWindow;
		
		public static function Instance():PopUpAutoCloseWindow
		{
			if (instance == null)
			{
				instance = new PopUpAutoCloseWindow();
			}
			
			return instance;
		}
		
		private var array:Array = new Array();		//窗口集合	
		
		public function open(window:IFlexDisplayObject, model:Boolean=true):void
		{
			array.push({'win':window,'mod':model});							
			var app:DisplayObject = FlexGlobals.topLevelApplication as DisplayObject;			
			PopUpManager.addPopUp(window, app, model);
			PopUpManager.centerPopUp(window);
			var timer:Timer = new Timer(2000);
			timer.addEventListener(TimerEvent.TIMER,onTimeout);
			timer.start();
		}
		
		private function onTimeout(e:TimerEvent):void
		{
			var t:Timer = e.target as Timer;
			t.stop();
			t = null;
			close();
		}
		
		public function close():void
		{
			if (array.length == 0)
			{
				return;
			}
			var obj:IFlexDisplayObject = array.pop()['win'] as IFlexDisplayObject; 			
			
			var pa:Parallel = new Parallel(obj);
			var me:Move = new Move();
			me.yFrom = obj.y;
			me.yTo = obj.y + 100;
			me.duration = 1000;
			pa.addChild(me);
			var fe:Fade = new Fade();
			fe.alphaFrom = 1;
			fe.alphaTo = 0;
			fe.duration = 1000;
			pa.addChild(fe);
			pa.addEventListener(EffectEvent.EFFECT_END,onEffectEnd);
			pa.play();
		}
		
		private function onEffectEnd(e:EffectEvent):void
		{
			var ef:Parallel = e.target as Parallel;
			var win:IFlexDisplayObject = ef.target as IFlexDisplayObject;
			ef.stop();
			PopUpManager.removePopUp(win);	
			ef = null;
		}
		
		public function closeAll():void
		{
			var len:int = array.length;
			while(len > 0)
			{
				close();
				len--;
			}
		}
		
	}
}